package com.changgou.filter;

import com.changgou.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @version v1.0
 * @ProjectName: changgou_parent
 * @ClassName: TokenFilter
 * @Description: TODO(令牌鉴权)
 * @Author: Xu Fj
 * @Date: 2020/2/24 17:10
 */
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "token";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //判断是否为登录请求
        if (request.getURI().getPath().contains("/admin/login")){
            return chain.filter(exchange);
        }

        //获取所有的请求头信息
        HttpHeaders headers = request.getHeaders();

        //拿到请求头信息中的令牌
        String token = headers.getFirst(AUTHORIZE_TOKEN);

        if (StringUtils.isEmpty(token)){
            //设置响应信息中的状态码
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //请求头中有令牌直接解析
        try {
            JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            //令牌过期或是令牌错误
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //令牌解析成功,放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
